package com.whenjun.interceptor;

import cn.dev33.satoken.interceptor.SaInterceptor;
import com.ifootbook.util.HttpUtil;
import com.ifootbook.util.NetUtil;
import com.ifootbook.util.Util;
import com.whenjun.entity.Request;
import com.whenjun.service.IRequestService;
import com.whenjun.util.SaTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.time.LocalDateTime;

/**
 * @Auther: whenjun
 * @Date: 2023/6/5 0005 14:29
 * @Description:
 */
@Component
public class ApiInterceptor extends SaInterceptor {

    @Autowired
    private IRequestService requestService;

    private static final Logger log = LoggerFactory.getLogger(ApiInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        if (method.equals("OPTIONS")) {
            return true;
        }

        String uri = request.getRequestURI();

        String ip = HttpUtil.getIpAddr(request);
        log.info("进入(api)拦截器:\n"
                + "ip:{}\n"
                + "请求地址：{}",ip,uri);

        ServletInputStream inputStream = request.getInputStream();
        String reqBody = StreamUtils.copyToString(inputStream, Charset.forName("UTF-8"));
        request.setAttribute("POST-DATA", reqBody);


        Request requestBean = new Request();
        String requestId = Util.getUUID32();
        requestBean.setId(requestId);
        requestBean.setIp(ip);
        requestBean.setMethod(method);
        requestBean.setUri(uri);
        requestBean.setRequestHeader(NetUtil.getAllHead(request));
        requestBean.setRequestBody(reqBody);
        requestBean.setRequestTime(LocalDateTime.now());
        requestBean.setUriParam(NetUtil.getUriParam(request));

        requestService.save(requestBean);

        // 放入当前请求存储器
        SaTokenUtil.setRequestId(requestId);

        return super.preHandle(request, response, handler);
    }
}
